import random

import logging
from django import http

# Create your views here.

from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import send_sms_code
# from meiduo_mall.libs.yuntongxun.ccp_sms import CCP
from meiduo_mall.utils.response_code import RETCODE
from verifcations import smstimes

logger = logging.getLogger('django')


class PictureView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')

        redis_conn.setex(uuid, smstimes.picture_second, text)

        return http.HttpResponse(image, content_type='image/jpg')


class SMSView(View):
    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_code')

        num = redis_conn.get('send_%s' % mobile)

        if num:
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR,
                                      'errmsg': '短信发送过于频繁'})

        sms_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([mobile, sms_code, uuid]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR,
                                      'errmsg': '未填写完整'})

        tiqu = redis_conn.get(uuid)
        if tiqu == None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR,
                                      'errmsg': '验证码已过期'})

        try:
            redis_conn.delete(uuid)
        except Exception as e:
            logger.error(e)

        if tiqu.decode().lower() != sms_code.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR,
                                      'errmsg': '验证码输入错误'})

        sms = '%06d' % random.randint(0, 999999)

        guandao = redis_conn.pipeline()

        guandao.setex(mobile, smstimes.sms_second, sms)

        guandao.setex('send_%s' % mobile, smstimes.sendtime, 1)

        guandao.execute()

        send_sms_code.delay(mobile, sms)

        # redis_conn.setex('sms_code_%s' % mobile,
        #                  constants.SMS_CODE_REDIS_EXPIRES,
        #                  sms_code)

        # 9. 发送短信验证码
        # 短信模板
        # SMS_CODE_REDIS_EXPIRES // 60 = 5min
        # SEND_SMS_TEMPLATE_ID = 1
        # CCP().send_template_sms(mobile, [sms_code, 5],
        #                         constants.SEND_SMS_TEMPLATE_ID)

        print(sms)

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok'})
